package com.taotao.admin.rest;

import com.rop.client.CompositeResponse;
import com.taotao.admin.DefaultRopClient;
import com.taotao.admin.MyRopClient;
import com.taotao.admin.pojo.TreeUI;
import com.taotao.rop.database.Constant;
import com.taotao.rop.database.domain.BaseDomain;
import com.taotao.rop.database.domain.Menu;
import com.taotao.rop.response.BaseResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

@Controller
@RequestMapping(value = "/menu")
public class MenuController {
    @RequestMapping(value = "/show", method = RequestMethod.POST)
    @ResponseBody
    public Object showMenu(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(new BaseDomain(), BaseResponse.class, "menu.show", "1.0");
        return setMenuResponse(response);
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Object getMenuList(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");

        CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                .post(new BaseDomain(), BaseResponse.class, "menu.list", "1.0");
        return setMenuResponse(response);
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(HttpServletRequest request) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        Menu menu = null;
        try {
            menu = getMenuFromRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (menu != null) {
            CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                    .post(menu, BaseResponse.class, "menu.insert", "1.0");
            if (response.isSuccessful()) {
                return response.getSuccessResponse();
            } else {
                return response.getErrorResponse().getSubErrors().get(0);
            }
        } else {
            BaseResponse resp = new BaseResponse();
            resp.setMsg("输入有误，请核对");
            return resp;
        }
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object update(HttpServletRequest request, @PathVariable String id) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        Menu menu = null;
        try {
            menu = getMenuFromRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (menu != null) {
            menu.setId(Long.parseLong(id));
            CompositeResponse<BaseResponse> response = MyRopClient.getRopClient(request.getHeader("sessionId")).buildClientRequest()
                    .post(menu, BaseResponse.class, "menu.update", "1.0");
            if (response.isSuccessful()) {
                return response.getSuccessResponse();
            } else {
                return response.getErrorResponse().getSubErrors().get(0);
            }
        } else {
            BaseResponse resp = new BaseResponse();
            resp.setMsg("输入有误，请核对");
            return resp;
        }
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object delete(HttpServletRequest request, @PathVariable String id) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        Menu menu = new Menu();
        menu.setId(Long.parseLong(id));
        menu.setStatus(Constant.STATUS_DELETE);
        DefaultRopClient ropClient = MyRopClient.getRopClient(request.getHeader("sessionId"));
        CompositeResponse<BaseResponse> response = ropClient.buildClientRequest()
                .post(menu, BaseResponse.class, "menu.update", "1.0");
        if (response.isSuccessful()){
            return response.getSuccessResponse();
        } else {
            return response.getErrorResponse().getSubErrors().get(0);
        }
    }

    private Object setMenuResponse(CompositeResponse<BaseResponse> response) {
        if (response.isSuccessful()) {
            BaseResponse respMenu = response.getSuccessResponse();
            if (respMenu.getSuccess()) {
                List<TreeUI> allTreeUI = new ArrayList<TreeUI>();
                List<LinkedHashMap<String, Object>> respData = (List<LinkedHashMap<String, Object>>) respMenu.getData();
                for (LinkedHashMap<String, Object> data : respData) {
                    List<LinkedHashMap<String, Object>> subTree = (List<LinkedHashMap<String, Object>>) data.get("subMenus");
                    TreeUI treeUI = new TreeUI();
                    treeUI.setId(Long.parseLong(data.get("id").toString()));
                    treeUI.setText(data.get("name").toString());
                    treeUI.setState("open");
                    List<TreeUI> children = new ArrayList<TreeUI>();
                    for (LinkedHashMap<String, Object> sub : subTree) {
                        TreeUI child = new TreeUI();
                        child.setId(Long.parseLong(sub.get("id").toString()));
                        child.setText(sub.get("name").toString());
                        LinkedHashMap<String, Object> attribute = new LinkedHashMap<String, Object>();
                        attribute.put("url", sub.get("url"));
                        child.setAttributes(attribute);
                        child.setParentId(Long.parseLong(sub.get("parentId").toString()));
                        child.setStatus(Integer.parseInt(sub.get("status").toString()));
                        child.setSort(Integer.parseInt(sub.get("sort").toString()));
                        if (sub.get("url") != null) {
                            child.setUrl(sub.get("url").toString());
                        }
                        children.add(child);
                    }
                    treeUI.setChildren(children);
                    treeUI.setParentId(Long.parseLong(data.get("parentId").toString()));
                    treeUI.setStatus(Integer.parseInt(data.get("status").toString()));
                    treeUI.setSort(Integer.parseInt(data.get("sort").toString()));
                    if (data.get("url") != null) {
                        treeUI.setUrl(data.get("url").toString());
                    }
                    allTreeUI.add(treeUI);
                }
                return allTreeUI;
            } else {
                return respMenu;
            }
        } else {
            return response.getErrorResponse().getSubErrors().get(0);
        }
    }

    private Menu getMenuFromRequest(HttpServletRequest request) throws Exception{
        String parentId = request.getParameter("parentId");
        String name = request.getParameter("name");
        String status = request.getParameter("status");
        String sort = request.getParameter("sort");
        String url = request.getParameter("url");

        Menu menu = new Menu();
        menu.setParentId(Long.parseLong(parentId));
        menu.setName(name);
        menu.setStatus(Integer.parseInt(status));
        if (sort != null) {
            menu.setSort(Integer.parseInt(sort));
        }
        menu.setUrl(url);
        return menu;
    }
}
